import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import { specialCharReg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTimePicker,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { useModel } from 'umi';
import { createShiftConfig } from '../../service';
import { CreateShiftConfigType } from '../../types.d';

const tranTime = (times: string[]) => {
  return times.map((item) => {
    const [h, m] = item.split(':');
    return parseInt(h) * 60 + parseInt(m);
  });
};

const CreateShiftConfig = (props: { reload: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  return (
    <ModalForm<CreateShiftConfigType & { timeFrames: string[] }>
      title="创建班次"
      width={800}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      trigger={
        <Button type="primary">
          <PlusOutlined /> 创建
        </Button>
      }
      onFinish={async (values) => {
        const { name, timeFrames: rawTime } = values;
        const timeFrames = tranTime(rawTime);
        const res = await createShiftConfig({
          name,
          timeFrames,
          ownerId: values.ownerId,
        });
        if (res.success) {
          message.success({ key: 'creaet_shfit', content: res.message });
          props.reload();
          return true;
        }
        message.error({ key: 'creaet_shfit', content: res.message });
        return false;
      }}
    >
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="归属公司"
          width="lg"
          debounceTime={300}
          showSearch
          placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      <ProFormText
        label="班次名称"
        width="lg"
        name="name"
        tooltip="公司下班次名称不可重复，名称中不得含有空白或特殊字符"
        rules={[
          {
            required: true,
            validator: (_, val) => {
              if (!val || val.length < 2 || val.length > 12)
                return Promise.reject(new Error('班次名称长度不符合要求，需要在2~12个字符之间'));
              if (specialCharReg.test(val))
                return Promise.reject(new Error('班次名称不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
        placeholder="请输入班次名称"
      />
      <ProFormTimePicker.RangePicker
        name="timeFrames"
        width="lg"
        label="工作时间"
        required
        tooltip="起始时间与结束时间相同时，表示全天24小时均为值班时间"
        placeholder={['起始时间', '结束时间']}
        fieldProps={{ format: 'HH:mm' }}
      />
    </ModalForm>
  );
};

export default CreateShiftConfig;
